package com.woniu.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.entity.*;
import com.woniu.mapper.*;
import com.woniu.service.IEverSalaryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lkl
 * @since 2020-11-29
 */
@Service
@Transactional
public class EverSalaryServiceImpl extends ServiceImpl<EverSalaryMapper, EverSalary> implements IEverSalaryService {
    @Resource
    private EverSalaryMapper salaryMapper;
    @Resource
    private EverEmpMapper empMapper;
    @Resource
    private EverSalerecordMapper salerecordMapper;
    @Resource
    private EverHouseMapper houseMapper;
    @Resource
    private EverOrderandsaleMapper orderandsaleMapper;
    /**
     * 查询所有人的工资 (包含财务已确认的 和 未确认的)
     * @return
     */
    @Override
    public List<EverSalary> findAll(String ename,
                                    Integer current,
                                    Integer size,
                                    Date starttime,
                                    Date endtime,
                                    String salstate
    ) {
        //根据ename模糊查询eid
        QueryWrapper<EverEmp> eq = new QueryWrapper<>();
        if(ename != null && !ename.equals("")){
            eq.like("ename",ename);
        }
        List<EverEmp> empList = empMapper.selectList(eq);
        List<Long> eidList = empList.stream().map(EverEmp::getEid).collect(Collectors.toList());
        //分页  注意要使用插件
        Page<EverSalary> page = new Page<>(current,size);
        QueryWrapper<EverSalary> wrapper = new QueryWrapper<>();
        wrapper
                .in("eid",eidList)
                .orderByDesc("saltime");
        if(starttime != null && !starttime.equals("")){
            wrapper.ge("saltime",starttime);
        }
        if(endtime != null && !endtime.equals("")) {
            wrapper.le("saltime",endtime);
        }
        if(salstate != null && !salstate.equals("")) {
            salstate = salstate.equals("1") ?"1": "2";
            wrapper.eq("salstate",salstate);
        }
        List<EverSalary> sums = salaryMapper.selectList(wrapper);
        Page<EverSalary> salaryList = salaryMapper.selectPage(page,wrapper);
        List<EverSalary> list = new ArrayList<>();
        for (EverSalary salary:salaryList.getRecords()
             ) {
            //获取到eid
            long eid2 = salary.getEid();
            //获取到这个员工信息
            EverEmp everEmp = empMapper.selectById(eid2);
            salary.setEmp(everEmp);
            //给前端分页传总的条数
            salary.setSum(sums.size());
            list.add(salary);
        }
        return list;
    }

    /**
     * 查询一条工资详情
     * @param sid
     * @return
     */
    @Override
    public EverSalary findOne(Integer sid) {
        return salaryMapper.selectById(sid);
    }

    /**
     * 修改一条工资的状态
     * @param salary
     * @return
     */
    @Override
    public Integer updateOne(EverSalary salary) {
        salary.setSaltime(new Date());
        salary.setSalstate("2");
        return salaryMapper.updateById(salary);
    }

    /**
     * 修改多条工资状态
     * @return
     */
    @Override
    public Integer updateMany(Long[] sids) {
        for (Long sid:sids
             ) {
            EverSalary salary = new EverSalary();
            salary.setSid(sid);
//            salary.setSaltime(new Date());
            salary.setSalstate("2");
            int i = salaryMapper.updateById(salary);
            if(i == 0){return i;}
        }
        return 1;
    }

    /**
     * 自动生成工资流水 默认工资是本月的营业额的 3% +基本工资    //如果是 本月第一天，就计算上个月员工的薪资
     * @return
     */
    @Override
    public void genSalary() throws ParseException {
        //获取当前时间
        Date date = new Date();
        //获取本月 零时到现在这段时间是否生成过工资
        Calendar calendar1=Calendar.getInstance();
        calendar1.set(Calendar.DAY_OF_MONTH, 1);
        SimpleDateFormat s = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String s1 = s.format(calendar1.getTime()).split(" ")[0];
        Date date1 = new Date(s1);
        QueryWrapper<EverSalary> qw = new QueryWrapper<>();
        qw.ge("saltime",date1);
        qw.le("saltime",date);
        //本月是否自动生成过工资
        List<EverSalary> salaryList = salaryMapper.selectList(qw);

        //延期时间
        long delay = 0;
        //间隔时间
        long period = 10000000;
        //对延期时间处理
        //下个月一号 0点的时间戳
        long time = 0l;
        //日期满足，并日本月没有生成过
        if(date.getDate() == 11 && salaryList.size() == 0){
            //延期时为：0
            //间隔时间为:
                 //获取当前的时间戳
            long l = System.currentTimeMillis();
                 //获取下个月一号 0时的时间戳
            Calendar nestMonthFirstDateCal = Calendar.getInstance();
            nestMonthFirstDateCal.add(Calendar.MONTH,+1);
            nestMonthFirstDateCal.set(Calendar.DAY_OF_MONTH, 1);
            Date nestMonthFirsttime = nestMonthFirstDateCal.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String format = sdf.format(nestMonthFirsttime);
            format = format.split(" ")[0] + " "+"00:00:00";
            nestMonthFirsttime = sdf.parse(format);
                 //获得下个月一号 0点的时间戳
            time = nestMonthFirsttime.getTime();
                 //间隔时间
            period = time - l;
        }
        else {
            //延期时间为：
                //获取当前的时间戳
            long l = System.currentTimeMillis();
            Calendar nestMonthFirstDateCal = Calendar.getInstance();
            nestMonthFirstDateCal.add(Calendar.MONTH,+1);
            nestMonthFirstDateCal.set(Calendar.DAY_OF_MONTH, 1);
            Date nestMonthFirsttime = nestMonthFirstDateCal.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String format = sdf.format(nestMonthFirsttime);
            format = format.split(" ")[0] + " "+"00:00:00";
            nestMonthFirsttime = sdf.parse(format);
               //获得下个月一号 0点的时间戳
            time = nestMonthFirsttime.getTime();
            delay = time - l;
            //对间隔时间的处理
                 //获取下两个月一号 0点的时间戳
            Calendar nest2MonthFirstDateCal = Calendar.getInstance();
            nest2MonthFirstDateCal.add(Calendar.MONTH,+2);
            nest2MonthFirstDateCal.set(Calendar.DAY_OF_MONTH, 1);
            Date nest2MonthFirsttime = nest2MonthFirstDateCal.getTime();
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            String format2 = sdf2.format(nest2MonthFirsttime);
            format2 = format2.split(" ")[0] + " "+"00:00:00";
            nest2MonthFirsttime = sdf2.parse(format2);
                 //获得下2个月一号 0点的时间戳
            long time2 = nest2MonthFirsttime.getTime();
                 //间隔时间
            period = time2 - time;
        }

//            验证间隔时间
//        System.out.println(period / 86400000+"((((((((((((((((((((((((((((");
        //获取下一个
        //完成一个计时器，当每月 第一天0点时处触发
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                 //工资 JDBC
                 salaryJDBC();
                }
                 //延迟3秒购，每隔10秒执行
            }, delay, period);
        }

    /**
     * JDBC工资（将新产生的基本工资持久化）
     */
    public void salaryJDBC(){
        //获取员工对象
        List<EverEmp> empList = empMapper.selectList(null);
        //获取所有员工的信息 （id）
        for (EverEmp emp:empList
        ) {
//            //如果是 本月第一天，就计算上个月员工的薪资
//            // 上月月第一天
            Calendar lastMonthFirstDateCal = Calendar.getInstance();
            lastMonthFirstDateCal.add(Calendar.MONTH,-1);
            lastMonthFirstDateCal.set(Calendar.DAY_OF_MONTH, 1);
            Date lastMonthFirsttime = lastMonthFirstDateCal.getTime();
            //本月的第一天
            Calendar thisMonthFirstDateCal = Calendar.getInstance();
            thisMonthFirstDateCal.set(Calendar.DAY_OF_MONTH, 1);
            Date thisMonthFirsttime = thisMonthFirstDateCal.getTime();
//            //获取在上月第一天到本月第一天的所有销售记录
            QueryWrapper<EverSalerecord> qw = new QueryWrapper<>();
            qw.ge("stime",lastMonthFirsttime);
            qw.le("stime",thisMonthFirsttime);
            qw.eq("eid",emp.getEid());
            List<EverSalerecord> salerecordList = salerecordMapper.selectList(qw);
            //汇总所有的 销售工资
//            EverSalerecord salarycord = new EverSalerecord();
            //用于记录 业务工资
            Double sumsalesal = 0.0;
            for (EverSalerecord salerecord: salerecordList
            ) {
                if (salerecord != null && salerecord.getMoney() != null) {
                    //获取所销售房屋的销售总价
                    sumsalesal += salerecord.getMoney().doubleValue();
                }
            }
            //将这个员工的工资数据保存到数据库
            EverSalary salary = new EverSalary();
            salary.setSal(emp.getSal());
            salary.setEid(emp.getEid());
            salary.setCommission(new BigDecimal(sumsalesal*0.01));
            salary.setSaltime(new Date());
            salary.setSalstate("1");
            salaryMapper.insert(salary);
        }
    }

    /**
     * 修改员工的基本工资
     * @param emp
     * @return
     */
    @Override
    public Integer changeSalary(EverEmp emp) {
        //修改员工表中的基本工资
        EverEmp emp1 = new EverEmp();
        emp1.setEid(emp.getEid());emp1.setSal(emp.getSal());
        empMapper.updateById(emp);
        //修改工资表中的基本工资
        EverSalary salary = new EverSalary();
        salary.setSid(emp.getSid());salary.setSal(emp.getSal());
        return salaryMapper.updateById(salary);
    }

    @Override
    public Page<EverSalary> findByEid(Integer eid, Integer size, Integer current) {
        Page<EverSalary> page = new Page<>(current, size);
        QueryWrapper<EverSalary> wrapper = new QueryWrapper<>();
        wrapper
                .eq("eid", eid)
                .orderByDesc("saltime");
        Page<EverSalary> everSalaryList = salaryMapper.selectPage(page,wrapper);
        //后台打印
        page.getRecords().forEach(System.out::println);
        //返回list时用
        List<EverSalary> records = everSalaryList.getRecords();
        return everSalaryList;
    }

    /**
     * 撤销对工资的审核
     * @param sid
     * @return
     */
    @Override
    public Integer returnSalary( Long sid) {
        EverSalary salary = new EverSalary();
        salary.setSid(sid);
        salary.setSalstate("1");
        return salaryMapper.updateById(salary);
    }

    /**
     * 查询工资  （数据导出）
     * @return
     */
    @Override
    public List<EverSalary> getsalary(String ename,
                                      Date starttime,
                                      Date endtime,
                                      String salstate) {
        //根据ename模糊查询eid
        QueryWrapper<EverEmp> eq = new QueryWrapper<>();
        if(ename != null && !ename.equals("")){
            eq.like("ename",ename);
        }
        List<EverEmp> empList = empMapper.selectList(eq);
        List<Long> eidList = empList.stream().map(EverEmp::getEid).collect(Collectors.toList());
        QueryWrapper<EverSalary> wrapper = new QueryWrapper<>();
        wrapper
                .in("eid",eidList)
                .orderByDesc("saltime");
        if(starttime != null && !starttime.equals("")){
            wrapper.gt("saltime",starttime);
        }
        if(endtime != null && !endtime.equals("")) {
            wrapper.lt("saltime",endtime);
        }
        if(salstate != null && !salstate.equals("")) {
            salstate = salstate.equals("1") ?"1": "2";
            wrapper.eq("salstate",salstate);
        }
        //默认导出上月的所有人的工资
        List<EverSalary> salaryList = salaryMapper.selectList(wrapper);
        for (int i = 0; i < salaryList.size(); i++) {
            EverEmp everEmp = empMapper.selectById(salaryList.get(i).getEid());
            salaryList.get(i).setEmp(everEmp);
        }
        return salaryList;
    }
}
